// utils/request.js
const BASE_URL = 'https://wechat.topucar.com/prod-api'; // 接口基础URL

// 封装请求函数
const request = (url, method, data = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url,
      method,
      data,
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token') || '' // 携带token
      },
      success: (res) => {
        debugger
        // 统一处理业务状态码
        if (res.data.code === 200) {
          resolve(res); // 返回业务数据
        } else {
          wx.showToast({
            title: res.data.message || '请求失败',
            icon: 'none'
          });
          reject(res);
        }
      },
      fail: (err) => {
        // 统一处理网络错误
        wx.showToast({
          title: `网络连接失败：${JSON.stringify(err)}`,
          icon: 'none'
        });
        reject(err);
      }
    });
  });
};

// 导出常用请求方法
module.exports = {
  get: (url, data) => request(url, 'GET', data),
  post: (url, data) => request(url, 'POST', data),
  put: (url, data) => request(url, 'PUT', data),
  delete: (url, data) => request(url, 'DELETE', data)
};